<?php
/**
 * 飞书登录回调处理
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 读取配置
$config = include __DIR__ . '/../../config.php';
$feishuConfig = $config['plugins']['feishu'] ?? [];

if (empty($feishuConfig['enabled']) || !$feishuConfig['enabled']) {
    die('飞书登录服务未启用');
}

// 获取回调参数
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';

if (empty($code)) {
    die('授权失败：缺少code参数');
}

// 验证state参数（防CSRF）
if (empty($_SESSION['feishu_state']) || $state !== $_SESSION['feishu_state']) {
    die('授权失败：state参数验证失败');
}

unset($_SESSION['feishu_state']);

$appId = $feishuConfig['app_id'];
$appSecret = $feishuConfig['app_secret'];

try {
    // 1. 获取 app_access_token
    $tokenUrl = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal';
    
    $tokenPostData = json_encode([
        'app_id' => $appId,
        'app_secret' => $appSecret
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $tokenUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $tokenPostData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $tokenData = json_decode($response, true);
    
    if (!isset($tokenData['app_access_token'])) {
        die('获取app_access_token失败：' . ($tokenData['msg'] ?? '未知错误'));
    }
    
    $appAccessToken = $tokenData['app_access_token'];
    
    // 2. 通过code换取用户信息
    $userUrl = 'https://open.feishu.cn/open-apis/authen/v1/access_token';
    
    $userPostData = json_encode([
        'grant_type' => 'authorization_code',
        'code' => $code
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $userUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $userPostData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $appAccessToken
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $userData = json_decode($response, true);
    
    if (!isset($userData['data'])) {
        die('获取用户信息失败：' . ($userData['msg'] ?? '未知错误'));
    }
    
    $userInfo = $userData['data'];
    $openId = $userInfo['open_id'] ?? '';
    $unionId = $userInfo['union_id'] ?? '';
    $userName = $userInfo['name'] ?? '飞书用户';
    
    if (empty($openId)) {
        die('未获取到用户唯一标识');
    }
    
    // 3. 检查是否与管理员配置中的飞书号匹配
    $adminFeishuId = $config['admin_user']['feishu_id'] ?? '';
    
    if (empty($adminFeishuId)) {
        die('管理员未配置飞书号，无法使用飞书登录');
    }
    
    // 匹配 open_id 或 union_id
    $isAuthorized = false;
    if ($adminFeishuId === $openId || (!empty($unionId) && $adminFeishuId === $unionId)) {
        $isAuthorized = true;
    }
    
    if (!$isAuthorized) {
        die('该飞书账号未授权登录，请联系管理员<br>当前 Open ID: ' . htmlspecialchars($openId) . (empty($unionId) ? '' : '<br>Union ID: ' . htmlspecialchars($unionId)));
    }
    
    // 4. 设置登录session
    $_SESSION['logged_in'] = true;
    $_SESSION['username'] = $config['admin_user']['username']; // 使用管理员配置的用户名
    $_SESSION['feishu_open_id'] = $openId;
    if (!empty($unionId)) {
        $_SESSION['feishu_union_id'] = $unionId;
    }
    $_SESSION['login_type'] = 'feishu';
    
    // 5. 跳转到首页
    header('Location: ../../index.php');
    exit;
    
} catch (Exception $e) {
    die('登录失败：' . $e->getMessage());
}
